// todo: Auth的viewmodel层
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../data/models/user.dart';
import '../../data/repositories/auth_repository.dart';

enum AuthStatus { initial, loading, success, error }

class AuthController extends StateNotifier<AuthStatus> {
  final AuthRepository authRepository;

  AuthController(this.authRepository) : super(AuthStatus.initial);

  Future<bool> login(User user) async {
    state = AuthStatus.loading;
    try {
      final success = await authRepository.login(user);
      state = success ? AuthStatus.success : AuthStatus.error;
      if (state == AuthStatus.success) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      state = AuthStatus.error;
      return false;
    }
  }

  Future<void> register(User user) async {
    state = AuthStatus.loading;
    try {
      final success = await authRepository.register(user);
      state = success ? AuthStatus.success : AuthStatus.error;
    } catch (e) {
      state = AuthStatus.error;
    }
  }
}

final authControllerProvider =
    StateNotifierProvider<AuthController, AuthStatus>((ref) {
  final authRepository = ref.watch(authRepositoryProvider);
  return AuthController(authRepository);
});
